package com.huaji.eat;

import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;

import android.content.Intent;
import android.os.Bundle;
import android.os.Environment;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.Toast;

import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;

public class FoodManaActivity extends AppCompatActivity {
    ArrayAdapter<String> adapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_food_mana);

        ListView list_food = findViewById(R.id.list_food);

        adapter = new ArrayAdapter<>(FoodManaActivity.this, R.layout.list_item);
        list_food.setAdapter(adapter);
        adapter.addAll(Data.foods);

        list_food.setOnItemClickListener((parent, view, position, id) -> {
            AlertDialog alertDialog = new AlertDialog.Builder(this)
                    .setTitle("删除")
                    .setMessage("确认删除吗？")
                    .setPositiveButton("确定", (dialog, which) -> {
                        Data.foods.remove(position);
                        adapter.clear();
                        adapter.addAll(Data.foods);
                        Toast.makeText(FoodManaActivity.this, "删除成功",Toast.LENGTH_LONG).show();
                    })
                    .setNegativeButton("取消", (dialog, which) -> Toast.makeText(FoodManaActivity.this, "不删除就别乱点",Toast.LENGTH_LONG).show())
                    .create();
            alertDialog.show();

        });

        Button btn_add = findViewById(R.id.btn_add);
        btn_add.setOnClickListener(v -> startActivity(new Intent().setClass(FoodManaActivity.this, AddFoodActivity.class)));
    }

    @Override
    protected void onPause() {
        super.onPause();

        try {
            FileOutputStream stream = new FileOutputStream("data/data/com.huaji.eat/data.bin");
            ObjectOutputStream object = new ObjectOutputStream(stream);
            object.writeObject(Data.foods);
            stream.close();
            object.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    protected void onResume() {
        super.onResume();

        adapter.clear();
        adapter.addAll(Data.foods);
    }
}
